import {
	generateSignature
} from "@/api/uploadFile.js"

export function uploadAvatar(avatar) {
	return new Promise((resolve, reject) => {
		uni.getFileSystemManager().getFileInfo({
			filePath: avatar,
			success: (res) => {
				// 进行大小判断
				const fileSize = res.size / 1024 / 1024
				if (fileSize > 3) {
					uni.showToast({
						title: '请选择不超过3M的图片，当前' + (fileSize).toFixed(2) + 'M',
						icon: 'none',
						duration: 3000
					}).then(() => {
						reject
					})
				} else {
					// 大小符合要求，进行签名
					generateSignature({
						uploadType: 0,
						fileType: avatar.split('.').pop()
					}).then((signData) => {
						console.log('signData', signData);
						let resData = signData.data
						//当前存储类型 1：七牛  2：阿里云  3：腾讯云
						if (resData.storageType === 2) {
							uni.uploadFile({
								url: resData.host, // 云存储上传接口URL
								filePath: avatar,
								name: 'file',
								formData: resData.data,
								success: function(res) {
									// 成功
									console.log("111", res);
									if (res.statusCode === 204) {
										resolve(resData.fileUrl)
									}
									if (res.statusCode === 400) {
										console.log("222", res.statusCode);
										uni.showToast({
											title: '图片上传失败：' + res.data,
											icon: 'fail'
										}).then(() => {
											reject
										})
									}
								},
								fail: function(err) {
									console.log("222");
									// 失败传base64文件
									resolve("data:image/jpeg;base64," + wx
										.getFileSystemManager()
										.readFileSync(
											avatar, 'base64'))
								}
							});

						} else {
							resolve("data:image/jpeg;base64," + uni.getFileSystemManager()
								.readFileSync(
									avatar, 'base64'))
						}
					}).catch(() => {
						resolve("data:image/jpeg;base64," + uni.getFileSystemManager()
							.readFileSync(
								avatar, 'base64'))
					})
				}
			},
			fail: (err) => {
				console.log("获取文件信息失败", err)
				reject
			}
		})

	})

}